<template>
	<view class="recipe-container">
		<!-- 加载错误状态 -->
		<view class="error-state" v-if="loadError">
			<image src="/static/images/no-data.png" mode="aspectFit" class="error-image"></image>
			<view class="error-text">加载失败</view>
			<view class="error-tips">{{errorMsg}}</view>
			<button class="retry-btn" @tap="loadRecipeDetail">重新加载</button>
		</view>
		
		<!-- 正常内容 -->
		<block v-else>
			<view class="recipe-header">
				<image :src="recipe.image || '/static/images/placeholder.png'" mode="aspectFill" class="recipe-image"></image>
				<view class="back-btn" @tap="goBack">
					<text class="iconfont icon-back"></text>
				</view>
			</view>
			
			<view class="recipe-content">
				<view class="recipe-title" @click="handleTitleClick">{{recipe.title || recipe.name || ''}}</view>
				<view class="recipe-desc">{{recipe.description || recipe.desc || ''}}</view>
				
				<view class="time-info">
					<view class="time-item">
						<text class="iconfont icon-time"></text>
						<text>准备时间: {{recipe.prepTime || 0}}分钟</text>
					</view>
					<view class="time-item">
						<text class="iconfont icon-fire"></text>
						<text>烹饪时间: {{recipe.cookTime || 0}}分钟</text>
					</view>
				</view>
				
				<view class="nutrition-card">
					<view class="nutrition-title">营养成分</view>
					<view class="nutrition-content">
						<view class="nutrition-item">
							<view class="nutrition-value">{{recipe.calories || 0}}</view>
							<view class="nutrition-label">卡路里(kcal)</view>
						</view>
						<view class="nutrition-item">
							<view class="nutrition-value">{{recipe.carbs || 0}}g</view>
							<view class="nutrition-label">碳水</view>
						</view>
						<view class="nutrition-item">
							<view class="nutrition-value">{{recipe.protein || 0}}g</view>
							<view class="nutrition-label">蛋白质</view>
						</view>
						<view class="nutrition-item">
							<view class="nutrition-value">{{recipe.fat || 0}}g</view>
							<view class="nutrition-label">脂肪</view>
						</view>
					</view>
				</view>
				
				<view class="ingredients-card">
					<view class="card-title">食材</view>
					<view class="ingredients-list">
						<view class="ingredient-item" v-for="(item, index) in recipeIngredients" :key="index">
							<text class="ingredient-name">{{item.foodName || item.name || '未命名食材'}}</text>
							<text class="ingredient-amount">{{item.quantity || item.amount || 0}} {{item.unit || 'g'}}</text>
						</view>
						<view v-if="recipeIngredients.length === 0" class="empty-tip">
							暂无食材信息
						</view>
					</view>
				</view>
				
				<view class="steps-card">
					<view class="card-title">步骤</view>
					<view class="steps-list">
						<view class="step-item" v-for="(step, index) in recipeSteps" :key="index">
							<view class="step-index">{{index + 1}}</view>
							<view class="step-content">{{step.content || step}}</view>
						</view>
						<view v-if="recipeSteps.length === 0" class="empty-tip">
							暂无步骤信息
						</view>
					</view>
				</view>
				
				<view class="tips-card" v-if="recipe.tips">
					<view class="card-title">小贴士</view>
					<view class="tips-content">{{recipe.tips}}</view>
				</view>
				
				<!-- 调试信息 -->
				<view class="debug-info" v-if="showDebug">
					<view class="card-title">调试信息</view>
					<view class="debug-content">
						<view>食谱ID: {{recipeId}}</view>
						<view>API响应码: {{apiResponseCode}}</view>
						<view>API消息: {{apiResponseMsg}}</view>
						<view>加载状态: {{isLoading ? '加载中' : '已加载'}}</view>
						<view>错误状态: {{loadError ? '有错误' : '无错误'}}</view>
						<view>错误信息: {{errorMsg}}</view>
						<view>食材数量: {{recipeIngredients.length}}</view>
						<view>食材数据源: {{getIngredientsSource()}}</view>
						<view>食材数据: {{JSON.stringify(recipeIngredients).substring(0, 100)}}</view>
					</view>
				</view>
			</view>
		</block>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import { getRecipeDetail } from '@/common/api/diet.js'
	
	// 调试模式
	const showDebug = ref(false)
	// API响应信息
	const apiResponseCode = ref(null)
	const apiResponseMsg = ref('')
	
	// 食谱ID
	const recipeId = ref(0)
	// 食谱详情
	const recipe = ref({
		ingredients: [],
		steps: []
	})
	// 加载状态
	const isLoading = ref(false)
	// 加载错误
	const loadError = ref(false)
	// 错误信息
	const errorMsg = ref('')
	
	// 处理食材数据，兼容不同的数据结构
	const recipeIngredients = computed(() => {
		if (recipe.value.meals && recipe.value.meals.length > 0) {
			console.log('使用meals数组中的食材数据:', recipe.value.meals.length)
			return recipe.value.meals
		} else if (recipe.value.ingredients && recipe.value.ingredients.length > 0) {
			console.log('使用ingredients数组中的食材数据:', recipe.value.ingredients.length)
			return recipe.value.ingredients
		} else if (recipe.value.foods && recipe.value.foods.length > 0) {
			console.log('使用foods数组中的食材数据:', recipe.value.foods.length)
			return recipe.value.foods
		} else {
			// 打印调试信息
			console.log('食谱无食材数据，食谱ID:', recipeId.value)
			return []
		}
	})
	
	// 处理步骤数据，兼容不同的数据结构
	const recipeSteps = computed(() => {
		if (recipe.value.steps && recipe.value.steps.length > 0) {
			return recipe.value.steps
		} else if (recipe.value.cookSteps && recipe.value.cookSteps.length > 0) {
			return recipe.value.cookSteps
		} else {
			return []
		}
	})
	
	// 获取URL参数
	onMounted(() => {
		console.log('食谱详情页面加载')
		
		// 尝试多种方式获取页面参数
		let id = null
		
		// 方法1: 通过getCurrentPages获取
		try {
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			console.log('当前页面:', currentPage ? currentPage.route : '未知')
			
			if (currentPage && currentPage.options) {
				console.log('页面参数(options):', JSON.stringify(currentPage.options))
				id = currentPage.options.id
			}
		} catch (e) {
			console.error('获取getCurrentPages失败:', e)
		}
		
		// 方法2: 通过系统信息判断平台
		if (!id) {
			try {
				const systemInfo = uni.getSystemInfoSync()
				console.log('系统平台:', systemInfo.platform)
				
				if (systemInfo.platform === 'mp-weixin') {
					const pages = getCurrentPages()
					const currentPage = pages[pages.length - 1]
					if (currentPage && currentPage.options) {
						console.log('微信小程序参数:', JSON.stringify(currentPage.options))
						id = currentPage.options.id
					}
				} else {
					const query = uni.getLaunchOptionsSync().query
					console.log('启动参数:', JSON.stringify(query))
					if (query && query.id) {
						id = query.id
					}
				}
			} catch (e) {
				console.error('获取系统信息失败:', e)
			}
		}
		
		// 方法3: 通过页面实例的$mp对象
		if (!id && this && this.$mp) {
			try {
				console.log('$mp参数:', JSON.stringify(this.$mp.query))
				id = this.$mp.query.id
			} catch (e) {
				console.error('获取$mp参数失败:', e)
			}
		}
		
		// 方法4: 尝试从URL中解析
		if (!id) {
			try {
				// 微信小程序环境下可能无法获取完整URL
				const pages = getCurrentPages()
				const currentPage = pages[pages.length - 1]
				const fullPath = currentPage ? currentPage.route : ''
				console.log('当前路径:', fullPath)
				
				// 尝试解析路径中的参数
				if (fullPath.includes('?')) {
					const queryPart = fullPath.split('?')[1]
					const params = new URLSearchParams(queryPart)
					id = params.get('id')
					console.log('从URL解析的ID:', id)
				}
			} catch (e) {
				console.error('从URL解析ID失败:', e)
			}
		}
		
		// 方法5: 从页面onLoad事件中获取
		// 这需要在页面配置中添加onLoad生命周期函数
		// 由于setup语法不支持直接访问onLoad，这里模拟一个全局变量
		if (!id && getApp().globalData && getApp().globalData.recipeParams) {
			id = getApp().globalData.recipeParams.id
			console.log('从全局变量获取ID:', id)
		}
		
		// 最终处理
		if (id) {
			recipeId.value = Number(id)
			console.log('成功获取食谱ID:', recipeId.value)
			loadRecipeDetail()
		} else {
			console.error('未能获取食谱ID')
			loadError.value = true
			errorMsg.value = '食谱ID不存在'
			uni.showToast({
				title: '食谱ID不存在',
				icon: 'none'
			})
		}
	})
	
	// 加载食谱详情
	const loadRecipeDetail = async () => {
		try {
			isLoading.value = true
			loadError.value = false
			errorMsg.value = ''
			
			uni.showLoading({
				title: '加载中...'
			})
			
			console.log('开始请求食谱详情, ID:', recipeId.value)
			const res = await getRecipeDetail({ id: recipeId.value })
			
			// 保存API响应信息
			apiResponseCode.value = res.code
			apiResponseMsg.value = res.msg || ''
			
			console.log('食谱详情API响应:', JSON.stringify(res).substring(0, 200))
			
			if (res.code === 0) {
				if (res.data) {
					recipe.value = res.data
					console.log('食谱详情数据:', JSON.stringify(recipe.value).substring(0, 200))
					
					// 调试食材数据
					console.log('食材数据结构:', 
						'meals:', recipe.value.meals ? recipe.value.meals.length : 'undefined', 
						'ingredients:', recipe.value.ingredients ? recipe.value.ingredients.length : 'undefined',
						'foods:', recipe.value.foods ? recipe.value.foods.length : 'undefined'
					)
					
					// 检查计算属性的结果
					console.log('计算后的食材列表:', recipeIngredients.value ? recipeIngredients.value.length : 0)
					if (recipeIngredients.value && recipeIngredients.value.length > 0) {
						console.log('第一个食材:', JSON.stringify(recipeIngredients.value[0]))
					}
					
					// 检查图片URL是否有效
					if (recipe.value.image) {
						checkImageUrl(recipe.value.image)
					}
				} else {
					console.error('食谱详情数据为空')
					loadError.value = true
					errorMsg.value = '食谱不存在'
					uni.showToast({
						title: '食谱不存在',
						icon: 'none'
					})
					
					// 延迟返回
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			} else {
				console.error('获取食谱详情失败:', res.msg)
				loadError.value = true
				errorMsg.value = res.msg || '加载失败'
				uni.showToast({
					title: res.msg || '加载失败',
					icon: 'none'
				})
			}
		} catch (e) {
			console.error('加载食谱详情异常:', e)
			loadError.value = true
			errorMsg.value = e.message || '加载异常'
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
			uni.hideLoading()
		}
	}
	
	// 检查图片URL是否有效
	const checkImageUrl = (url) => {
		if (!url) return
		
		uni.getImageInfo({
			src: url,
			success: () => {
				console.log('图片URL有效:', url)
			},
			fail: () => {
				console.error('图片URL无效:', url)
				// 如果图片无效，使用默认图片
				recipe.value.image = '/static/images/placeholder.png'
			}
		})
	}
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
	
	// 处理标题点击事件
	const handleTitleClick = () => {
		// 简单的计数器实现
		const now = Date.now()
		// 使用全局变量存储状态
		getApp().globalData = getApp().globalData || {}
		getApp().globalData.lastTitleClickTime = getApp().globalData.lastTitleClickTime || 0
		getApp().globalData.titleClickCount = getApp().globalData.titleClickCount || 0
		
		if (now - getApp().globalData.lastTitleClickTime < 500) {
			getApp().globalData.titleClickCount++
			if (getApp().globalData.titleClickCount >= 5) {
				showDebug.value = !showDebug.value
				uni.showToast({
					title: showDebug.value ? '调试模式已开启' : '调试模式已关闭',
					icon: 'none'
				})
				getApp().globalData.titleClickCount = 0
			}
		} else {
			getApp().globalData.titleClickCount = 1
		}
		getApp().globalData.lastTitleClickTime = now
	}
	
	// 获取食材数据来源
	const getIngredientsSource = () => {
		if (recipe.value.meals && recipe.value.meals.length > 0) {
			return `meals数组 (${recipe.value.meals.length}个食材)`
		} else if (recipe.value.ingredients && recipe.value.ingredients.length > 0) {
			return `ingredients数组 (${recipe.value.ingredients.length}个食材)`
		} else if (recipe.value.foods && recipe.value.foods.length > 0) {
			return `foods数组 (${recipe.value.foods.length}个食材)`
		} else {
			return '无有效数据源'
		}
	}
</script>

<style lang="scss">
	.recipe-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		
		.error-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 100rpx 0;
			
			.error-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 30rpx;
			}
			
			.error-text {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.error-tips {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 30rpx;
			}
			
			.retry-btn {
				width: 240rpx;
				height: 70rpx;
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				border-radius: 35rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
		
		.recipe-header {
			position: relative;
			height: 400rpx;
			
			.recipe-image {
				width: 100%;
				height: 100%;
				background-color: #f0f0f0;
				object-fit: cover;
			}
			
			.back-btn {
				position: absolute;
				top: 40rpx;
				left: 30rpx;
				width: 70rpx;
				height: 70rpx;
				background-color: rgba(255, 255, 255, 0.8);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.icon-back {
					font-size: 36rpx;
					color: #333;
				}
			}
		}
		
		.recipe-content {
			padding: 30rpx;
			margin-top: -40rpx;
			border-radius: 40rpx 40rpx 0 0;
			background-color: #fff;
			position: relative;
			
			.recipe-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.recipe-desc {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
				line-height: 1.5;
			}
			
			.time-info {
				display: flex;
				margin-bottom: 30rpx;
				
				.time-item {
					display: flex;
					align-items: center;
					margin-right: 30rpx;
					font-size: 26rpx;
					color: #666;
					
					.iconfont {
						font-size: 28rpx;
						margin-right: 8rpx;
						color: #8cc9a1;
					}
				}
			}
			
			.nutrition-card {
				background-color: #f8f8f8;
				border-radius: 12rpx;
				padding: 20rpx;
				margin-bottom: 30rpx;
				
				.nutrition-title {
					font-size: 30rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 15rpx;
				}
				
				.nutrition-content {
					display: flex;
					justify-content: space-between;
					
					.nutrition-item {
						text-align: center;
						
						.nutrition-value {
							font-size: 32rpx;
							font-weight: bold;
							color: #333;
							margin-bottom: 5rpx;
						}
						
						.nutrition-label {
							font-size: 24rpx;
							color: #999;
						}
					}
				}
			}
			
			.ingredients-card, .steps-card, .tips-card, .debug-info {
				margin-bottom: 30rpx;
				
				.card-title {
					font-size: 30rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 20rpx;
					position: relative;
					padding-left: 20rpx;
					
					&::before {
						content: '';
						position: absolute;
						left: 0;
						top: 50%;
						transform: translateY(-50%);
						width: 6rpx;
						height: 30rpx;
						background-color: #8cc9a1;
						border-radius: 3rpx;
					}
				}
				
				.empty-tip {
					font-size: 28rpx;
					color: #999;
					text-align: center;
					padding: 20rpx 0;
				}
			}
			
			.ingredients-card {
				.ingredients-list {
					.ingredient-item {
						display: flex;
						justify-content: space-between;
						padding: 15rpx 0;
						border-bottom: 1px solid #f0f0f0;
						
						&:last-child {
							border-bottom: none;
						}
						
						.ingredient-name {
							font-size: 28rpx;
							color: #333;
						}
						
						.ingredient-amount {
							font-size: 28rpx;
							color: #666;
						}
					}
				}
			}
			
			.steps-card {
				.steps-list {
					.step-item {
						display: flex;
						margin-bottom: 20rpx;
						
						&:last-child {
							margin-bottom: 0;
						}
						
						.step-index {
							width: 50rpx;
							height: 50rpx;
							background-color: #8cc9a1;
							color: #fff;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 28rpx;
							margin-right: 20rpx;
							flex-shrink: 0;
						}
						
						.step-content {
							flex: 1;
							font-size: 28rpx;
							color: #333;
							line-height: 1.5;
							padding-top: 10rpx;
						}
					}
				}
			}
			
			.tips-card {
				.tips-content {
					font-size: 28rpx;
					color: #666;
					line-height: 1.5;
					padding: 20rpx;
					background-color: #f8f8f8;
					border-radius: 12rpx;
					border-left: 4rpx solid #8cc9a1;
				}
			}
			
			.debug-info {
				margin-top: 40rpx;
				border-top: 1px dashed #ccc;
				padding-top: 20rpx;
				
				.debug-content {
					font-size: 24rpx;
					color: #999;
					line-height: 1.8;
					font-family: monospace;
				}
			}
		}
	}
</style> 